package com.pandi.springboot_jwt.exception;


import com.auth0.jwt.exceptions.JWTDecodeException;
import com.pandi.springboot_jwt.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.List;

/**
 * @author pandi
 * @create 2021-01-03 17:13
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice extends ResponseEntityExceptionHandler {

    @Override
    public ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<>(getError(ex.getBindingResult().getAllErrors()) , status);
    }


    /**
     * 解决 JSON 请求统一返回参数
     */
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<>(getError(ex.getBindingResult().getAllErrors()) , status);
    }

    private Result getError(List<ObjectError> allErrors) {
        StringBuffer message = new StringBuffer();
        for(ObjectError error: allErrors){
            message.append(error.getDefaultMessage()).append(" & ");
        }
        log.error(message.substring(0, message.length() - 3));  // 因为&两边空格
        return new Result().setError(message.substring(0, message.length() - 3));
    }

    @ResponseBody
    @ExceptionHandler(JWTDecodeException.class)
    public Result jwterror(JWTDecodeException ex){
        Result result = new Result();
        result.setErrorMessage(ex.getMessage());
        return result;
    }

    @ResponseBody
    @ExceptionHandler(value={AuthorizationException.class, UnauthorizedException.class})
    public Result unAuthorizationExceptionHandler(Exception e){
        Result result = new Result();
        result.setData("您暂无权限！");
        return result;
    }



}
